package com.yt.product.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import com.yt.product.models.service.IProductCategoryService;
import com.yt.product.models.bo.ProductCategoryBO;
import com.yt.product.models.dto.ProductCategoryDTO;

import java.util.Date;
import java.util.Map;

/**
 * 产品类别信息控制器
 * （负责处理 /api/productCategory 前缀的接口，匹配前端请求路径）
 *
 * @author lianyadong
 * @Date 2025-09-03 14:16:35
 */
@RestController
@RequestMapping("/api/productCategory")
@Slf4j
@Api(value = "ProductCategoryApiController", tags = "产品类别信息Api接口")
public class ProductCategoryApiController {

    @DubboReference
    private IProductCategoryService productCategoryService;

    // 根据ID查询产品类别详情
    @PostMapping("/get")
    @ApiOperation(value = "根据id查找", notes = "根据产品类别ID查询详情")
    @ApiImplicitParam(name = "id", value = "产品类别ID", required = true, paramType = "query", dataType = "Long")
    public Result<ProductCategoryDTO> get(@RequestParam("id") Long id) {
        if (id == null || id <= 0) {
            log.warn("查询产品类别失败：ID无效（id={}）", id);
            return new Result<>(CodeEnum.FAIL_100002);
        }

        ProductCategoryDTO dto = productCategoryService.selectById(id);
        log.info("查询产品类别结果：ID={}，存在={}", id, dto != null);
        return new Result<>(dto);
    }

    // 分页查询产品类别列表
    @PostMapping("/queryPageList")
    @ApiOperation(value = "产品类别信息列表", notes = "分页查询产品类别，支持状态、创建时间范围筛选")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "当前页码", defaultValue = "1", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", defaultValue = "10", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "status", value = "状态（0=禁用，1=启用，2=已删除）", required = false, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "startDate", value = "创建时间起始（格式：yyyy-MM-dd HH:mm:ss）", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "创建时间结束（格式：yyyy-MM-dd HH:mm:ss）", required = false, paramType = "query", dataType = "String")
    })
    public Result<Page<ProductCategoryDTO>> queryPageList(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize,
            ProductCategoryBO bo) {

        // 处理分页参数
        int validPageNo = Math.max(pageNo, 1);
        int validPageSize = Math.min(Math.max(pageSize, 1), 100);
        Page<ProductCategoryDTO> page = new Page<>(validPageNo, validPageSize);

        // 构建查询条件
        Wrapper<ProductCategoryDTO> wrapper = new EntityWrapper<>();
        wrapper.ne("status", 2) // 排除已删除数据
                .orderBy("update_time", false); // 按更新时间降序

        // 动态筛选条件
        if (bo != null) {
            if (bo.getStatus() != null) {
                wrapper.eq("status", bo.getStatus());
                log.info("产品类别列表筛选：状态={}", bo.getStatus());
            }
            if (bo.getStartDate() != null) {
                wrapper.ge("create_time", bo.getStartDate());
                log.info("产品类别列表筛选：创建时间≥{}", bo.getStartDate());
            }
            if (bo.getEndDate() != null) {
                wrapper.le("create_time", bo.getEndDate());
                log.info("产品类别列表筛选：创建时间≤{}", bo.getEndDate());
            }
        }

        // 查询分页数据
        Page<ProductCategoryDTO> resultPage = productCategoryService.selectPage(page, wrapper);
        log.info("产品类别分页查询完成：页码={}，条数={}，总记录数={}", validPageNo, validPageSize, resultPage.getTotal());

        return new Result<>(resultPage);
    }

    // 更新产品类别状态
    @PostMapping("/updateStatus")
    @ApiOperation(value = "更新产品类别状态", notes = "启用/禁用产品类别，status=1启用，status=0禁用；不允许设置为2（已删除）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "产品类别ID", required = true, paramType = "body", dataType = "Long"),
            @ApiImplicitParam(name = "status", value = "目标状态（0=禁用，1=启用）", required = true, paramType = "body", dataType = "Integer")
    })
    public Result updateStatus(@RequestBody Map<String, Object> params) {
        // 解析参数
        Long id = parseLongParam(params.get("id"), "产品类别ID");
        Integer status = parseIntegerParam(params.get("status"), "状态");

        // 基础校验
        if (id == null) return new Result<>(CodeEnum.FAIL_100002);
        if (status == null || (status != 0 && status != 1)) {
            log.warn("更新产品类别状态失败：无效状态值（status={}）", status);
            return new Result<>(CodeEnum.FAIL_100003);
        }

        // 检查数据状态
        ProductCategoryDTO existDto = productCategoryService.selectById(id);
        if (existDto == null) {
            log.warn("更新产品类别状态失败：ID={}不存在", id);
            return new Result<>(CodeEnum.FAIL_100004);
        }
        if (existDto.getStatus() == 2) {
            log.warn("更新产品类别状态失败：ID={}已删除", id);
            return new Result<>(CodeEnum.FAIL_100005);
        }
        if (existDto.getStatus().equals(status)) {
            log.info("产品类别状态未变更：ID={}，状态={}", id, status);
            return new Result<>();
        }

        // 执行更新
        ProductCategoryDTO updateDto = new ProductCategoryDTO();
        updateDto.setId(id);
        updateDto.setStatus(status);
        updateDto.setUpdateTime(new Date());

        boolean success = productCategoryService.updateById(updateDto);
        log.info("更新产品类别状态{}：ID={}，旧状态={}，新状态={}",
                success ? "成功" : "失败", id, existDto.getStatus(), status);

        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100006);
    }

    // 软删除产品类别
    @PostMapping("/delete")
    @ApiOperation(value = "删除产品类别", notes = "软删除：将状态改为2（已删除），不物理删除数据")
    @ApiImplicitParam(name = "id", value = "产品类别ID", required = true, paramType = "body", dataType = "Long")
    public Result delete(@RequestBody Map<String, Object> params) {
        // 解析参数
        Long id = parseLongParam(params.get("id"), "产品类别ID");
        if (id == null) return new Result<>(CodeEnum.FAIL_100002);

        // 检查数据状态
        ProductCategoryDTO existDto = productCategoryService.selectById(id);
        if (existDto == null) {
            log.warn("删除产品类别失败：ID={}不存在", id);
            return new Result<>(CodeEnum.FAIL_100004);
        }
        if (existDto.getStatus() == 2) {
            log.info("产品类别已删除：ID={}", id);
            return new Result<>();
        }

        // 执行软删除
        ProductCategoryDTO deleteDto = new ProductCategoryDTO();
        deleteDto.setId(id);
        deleteDto.setStatus(2);
        deleteDto.setUpdateTime(new Date());

        boolean success = productCategoryService.updateById(deleteDto);
        log.info("软删除产品类别{}：ID={}，原状态={}",
                success ? "成功" : "失败", id, existDto.getStatus());

        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100006);
    }

    // 参数解析工具方法
    private Long parseLongParam(Object param, String paramName) {
        if (param == null) {
            log.warn("参数{}为空", paramName);
            return null;
        }
        try {
            return Long.valueOf(param.toString().trim());
        } catch (NumberFormatException e) {
            log.warn("参数{}格式错误：{}", paramName, param);
            return null;
        }
    }

    private Integer parseIntegerParam(Object param, String paramName) {
        if (param == null) {
            log.warn("参数{}为空", paramName);
            return null;
        }
        try {
            return Integer.valueOf(param.toString().trim());
        } catch (NumberFormatException e) {
            log.warn("参数{}格式错误：{}", paramName, param);
            return null;
        }
    }
}


